<template>

  <popup :title="title" @confirm="handleSubmit" ref="popupRef">

    <el-form :model="formData" :rules="rules" ref="formRef" label-width="10%">
      <el-form-item label="名称" prop="name">
        <el-input
            v-model="formData.name"
            placeholder="请输入名称"
            clearable
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">正常</el-radio>
          <el-radio :label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="值" prop="value">
        <el-input
            v-model="formData.value"
            placeholder="请输入值"
            clearable
        />
      </el-form-item>

      <el-form-item label="备注" prop="memo">
        <el-input
            v-model="formData.memo"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入备注"
            maxlength="200"
            show-word-limit
        />
      </el-form-item>
    </el-form>

  </popup>

</template>

<script setup>
import popup from '@/components/popup/index.vue'
import {reactive, ref, shallowRef} from "vue";
import {add, edit} from '@/api/dictDetail'
import FormInstance from 'element-plus'

const formRef = shallowRef(FormInstance)
const popupRef = shallowRef(popup)
const emit = defineEmits(['success'])

const title = ref('edit')
const formData = reactive({
  dict_code: '',
  id: 0,
  name: '',
  value: '',
  status: 0,
  memo: ''
})

const rules = reactive({
  name: [
    {required: true, message: '请输入名称', trigger: 'blur'},
  ],
  value: [
    {required: true, message: '请输入值', trigger: 'blur'},
  ],
})

const handleSubmit = async () => {
  await formRef.value?.validate()
  title.value === 'edit' ? await edit(formData) : await add(formData)
  emit('success')
}

const setFormData = async (data = {}, name = 'add') => {
  title.value = name

  if (Object.keys(data).length > 0) {
    for (const key in formData) {
      if (data[key] !== null && data[key] !== undefined) {
        formData[key] = data[key]
      }
    }
  }
}

defineExpose({
  setFormData
})
</script>

<style scoped>

</style>